import { Component, NgZone, OnInit, Inject } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { TranslateService } from '@ngx-translate/core';
import { RestService } from '../../services/rest.service';
import { ActionTypes, DialogTypes } from '../../models/wdl-types';

import * as _ from 'lodash';

@Component({
  selector: 'app-department-dialog',
  templateUrl: './department-dialog.component.html',
  styleUrls: ['./department-dialog.component.css']
})
export class DepartmentDialogComponent implements OnInit {
  formGroup: FormGroup;
  item: any;
  institution: any;
  title = '';
  oldDepartmentName = '';

  // could be add, modify
  mode = ActionTypes.ADD;
  disabled = false;
  error = '';

  constructor(@Inject(MAT_DIALOG_DATA) private dialogData: any,
              public dialogRef: MatDialogRef<DepartmentDialogComponent>,
              fb: FormBuilder,
              private ngZone: NgZone,
              private translate: TranslateService,
              private rest: RestService,
              private dialog: MatDialog) {
    this.item = dialogData.item;
    this.institution = dialogData.institution;
    this.mode = dialogData.mode;

    if (this.mode === ActionTypes.ADD) {
      this.title = this.translate.get('add')['value'] + this.translate.get('department')['value'];
    } else if (this.mode === ActionTypes.MODIFY) {
      this.title = this.translate.get('edit')['value'];
      this.oldDepartmentName = this.item['departmentName'];
    }

    this.formGroup = fb.group({
      departmentName: [
        '',
        [ Validators.required, Validators.maxLength(128) ]
      ]
    });

    if (this.mode !== ActionTypes.ADD) {
      _.forEach(this.formGroup.controls, (value, key) => {
        value.value = this.item[key];
      });
    }
  }

  disableSubmit() {
    return this.formGroup.invalid || (this.mode === ActionTypes.MODIFY && !this.formGroup.dirty);
  }

  checkChild(name, succ, fail) {
    if (this.mode === ActionTypes.MODIFY && this.oldDepartmentName === name) {
      if (succ) {
        succ();
        return;
      }
    }

    this.rest.getWithParams('data/department/search/name', {
      institutionId: this.institution.id,
      name: name,
      size: 100
    }).subscribe(data => {
      const children = data['_embedded']['departments'];
      if (children && children.length > 0) {
        let duplicate = false;
        children.forEach(depart => {
          if (name === depart['departmentName']) {
            duplicate = true;
          }
        });

        if (duplicate) {
          if (fail) {
            fail();
          }
        } else {
          if (succ) {
            succ();
          }
        }
      } else {
        if (succ) {
          succ();
        }
      }
    }, () => {
      if (fail) {
        fail();
      }
    });
  }

  submit() {
    const data = {};
    _.forEach(this.formGroup.value, (value, key) => {
      data[key] = _.trim(value);
    });

    this.error = '';
    this.checkChild(data['departmentName'], () => {
      this.dialogRef.close(data);
    }, () => {
      this.error = this.translate.get('duplicateDepartmentName')['value'];
    });
  }

  ngOnInit() {
  }
}
